Tanstack Routerでfile-based routing
from TanStack Router
file-system based routingできる
https://tanstack.com/router/v1/docs/framework/react/routing/file-based-routing
https://tanstack.com/router/latest/docs/framework/react/routing/file-based-routing
https://tanstack.com/router/latest/docs/framework/react/routing/file-naming-conventions
code:_
src/
├── routes/ ← route 定義
│ ├── __root.tsx ← routeのRoot(createRootRoute)
│ │ <Outlet />で子ルートをレンダリング
│ │ 共通の <Link> やナビゲーション
│ │
│ ├── index.tsx ← "/" に対応(createFileRoute("/"))
│ └── about.tsx ← "/about" に対応(createFileRoute("/about"))
│
├── main.tsx ← エントリーポイント
│ routeTree.gen.ts を import
│ createRouter({ routeTree }) でルーター作成
│ <RouterProvider router={router} />
│
├── 📄 routeTree.gen.ts ← tsrで自動生成される
ファイル構造に基づいてルートツリーを構築
src/routes/__root.tsx
https://tanstack.com/router/latest/docs/framework/react/quick-start#srcroutes__roottsx
createRootRouteを使う
他では、 createFileRoute を使ってルートを定義
https://tanstack.com/router/latest/docs/framework/react/quick-start#srcroutesindextsx
code:ts
import { createFileRoute } from '@tanstack/react-router'
export const Route = createFileRoute('/posts/$postId')({
loader: async ({ params }) => fetchPost(params.postId),
component: PostPage,
errorComponent: ErrorComponent,
pendingComponent: LoadingComponent,
})
file basedだけど'/posts/$postId'は自分で指定するんやmrsekut.icon
自動で型推論されるので params.postId は型安全
エントリポイント
createRouter
ルーターインスタンスの作成
https://tanstack.com/router/latest/docs/framework/react/quick-start#srcmaintsx
bun run devして起動し続けてると
λ bun tsr generateも自動で行われるし、
src/routes/内にtsファイルを作ると、自動でrouteの雛形が作られて体験が良い
命名規則キツイ
https://tanstack.com/router/latest/docs/framework/react/routing/file-based-routing#directory-routes
特殊ファイル・接頭辞
__root.tsx
アプリ全体のルート。
全ページで最上位にレンダリングされる <Root> 的なもの
index.tsx / xxx.index.tsx
そのセグメント直下のインデックス(完全一致)。
ディレクトリ例:posts/index.tsx → /posts に完全一致
フラット例:posts.index.tsx も同じ意味
route.tsx
そのディレクトリ自身のページ(“/account” など)を表すエントリ。
account/route.tsx → /account
_xxxx(先頭アンダースコア)
パスに現れない“レイアウト専用”。
URL セグメントを増やさずにレイアウトを挟みたい時。
例:_pathlessLayout.tsx、_pathlessLayout.route-a.tsx → /route-a だが中で <PathlessLayout> を噛ませる
xxx_(末尾アンダースコアのディレクトリ)
**親レイアウトに乗らない“パスだけ継承”**のために使うパターン
例にある posts_/$postId/edit が <Posts> レイアウトを通らず <Root><EditPost> だけになる
要は「URL は /posts/... だが、posts レイアウトは適用しない」ための脱出ハッチ。
動的パラメータ・スプラット
$param.tsx / xxx.$param.tsx
動的セグメント。
$postId → :postId
$.tsx / xxx.$.tsx
スプラット(キャッチオール)。そ
の位置以降を丸ごと受ける
例:files.$.tsx → /files/*(残り全部をキャプチャ)
ディレクトリ vs フラットの対応関係
ディレクトリ:
code:_
posts/
index.tsx -> /posts (exact)
$postId.tsx -> /posts/:postId
$postId.edit.tsx -> /posts/:postId/edit (ミックス例)
フラット:
code:_
posts.tsx -> /posts(親レイアウト)
posts.index.tsx -> /posts (exact)
posts.$postId.tsx -> /posts/:postId
posts.$postId.edit.tsx -> /posts/:postId/edit
レイアウトの考え方
posts.tsx(フラット)や posts/route.tsx(ディレクトリ)が親レイアウトになるイメージ。
それ配下の index.tsx や $postId.tsx は子ルートとして親の中にレンダリングされる。
_pathlessLayout* はURL に現れないレイアウトだけを差し込むテク。
posts_ のような末尾アンダースコアは「その親レイアウトをバイパスしたい」時に使える。